import { ScrollView, Text, View } from "@tarojs/components";

import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import Footer from "@/components/Footer/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import {
  Button,
  Image,
  Pagination,
  Checkbox,
  Popup,
  Form,
  Cell,
  Input,
  Toast,
  Dialog,
  Radio,
  Field,
  Picker,
  Textarea,
  ConfigProvider,
} from "@taroify/core";
import { useEffect, useRef, useState } from "react";
import { ArrowDown, PhotoFail } from "@taroify/icons";
import { requestGET, requestPOST, requestPUT } from "@/request";
import Taro from "@tarojs/taro";
import { FormInstance, FormItemInstance } from "@taroify/core/form";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import FormLabel from "@taroify/core/form/form-label";

export default function Index() {
  const [active, setActive] = useState(0);
  const [list, setList] = useState<any>([]);
  const [current, setCurrent] = useState(1);
  const [count, setCount] = useState(0);
  const [selectId, setSelectId] = useState<any>([]);
  const [open, setOpen] = useState(false);
  const [open1, setOpen1] = useState(false);
  const [form, setForm] = useState({
    id: "",
    detailId: "",
    price: "",
    quantity: "",
  });
  const [form1, setForm1] = useState<any>({});
  const ref = useRef<FormInstance>(null);
  const ref1 = useRef<FormInstance>(null);
  const ref2 = useRef<FormInstance>(null);
  const ref3 = useRef<FormInstance>(null);
  const [open2, setOpen2] = useState(false);
  const [form2, setForm2] = useState<any>({
    orderNo: "",
    toUser: "",
    backEmail: "",
  });
  const shopInfo = useSelector((state: RootState) => state.userInfo.shopInfo);
  const [open3, setOpen3] = useState(false);
  const [form3, setForm3] = useState<any>({
    commodityId: "",
  });
  const itemRef = useRef<FormItemInstance>();
  const [open4, setOpen4] = useState(false);

  const businessId = useSelector(
    (state: RootState) => state.business.businessId
  );

  const [productList, setProductList] = useState<any>([]);

  const getProductList = () => {
    requestPOST("index/keywordSearch", {
      businessId: businessId,
      pageNum: 1,
      pageSize: 1000,
      keyword: "",
    }).then((res: any) => {
      setProductList(
        [...res.vos].map((item) => ({
          ...item,
          label: item.commodityName,
          value: item.id,
        }))
      );
    });
  };

  const getList = (page?: number, active1?: number) => {
    requestPOST(`shop/shopOrderList`, {
      pageTotal: 27,
      pageNum: page || current,
      pageSize: 5,
      orderStatus: active1 === undefined ? active : active1,
      isSettlement: 0,
    }).then((res: any) => {
      setCount(Math.ceil(res.total / 5));
      setList([...res.vos].map((item) => ({ ...item, show: false })));
    });
  };

  const handleChange = (page) => {
    setCurrent(page);
    getList(page);
  };

  const handleShow = (item, index) => {
    let data = { ...item, show: !item.show };
    list.splice(index, 1, data);
    setList([...list]);
  };

  const editPrice = (item, order) => {
    setForm({
      ...form,
      id: item.id,
      detailId: order.id,
      price: order.price,
      quantity: order.quantity,
    });
    setOpen(true);
  };

  const onSubmit = () => {
    requestPUT("shop/updateDetailOrder", { ...form }).then(() => {
      Toast.open({ type: "success", message: "保存成功" });
      setOpen(false);
      setForm({
        id: "",
        detailId: "",
        price: "",
        quantity: "",
      });
      formRef.current?.reset();
      getList();
    });
  };

  const cancelOrder = (item) => {
    Dialog.confirm({
      title: "提示",
      message: "您确定要解绑吗？",
      onConfirm() {
        requestPOST("shop/shopCancelOrder", {
          backEmail: item.orderNo,
          orderType: item.orderType,
        }).then(() => {
          Toast.open({ type: "success", message: "取消成功" });
          getList();
        });
      },
    });
  };

  const viewImage = (item) => {
    Taro.previewMedia({
      sources: [{ url: process.env.TARO_APP_API + item.payVoucher }],
      current: 0,
    });
  };

  const confirmOrderPayApi = (item) => {
    Dialog.confirm({
      title: "提示",
      message:
        "此操作将确认离线付款订单 " + item.orderNo + " 已付款，是否继续?",
      onConfirm() {
        requestPOST("/shop/confirmOrderPay", {
          orderNo: item.orderNo,
          orderType: item.orderType,
        }).then(() => {
          Toast.open({ type: "success", message: "操作成功" });
          getList();
        });
      },
    });
  };

  const shopConfirmOrderPay = (item) => {
    Dialog.confirm({
      title: "提示",
      message: "是否确认支付?",
      onConfirm() {
        requestPOST(`shop/shopConfirmOrderPay/` + item.orderNo).then(() => {
          Toast.open({ type: "success", message: "操作成功" });
          getList();
        });
      },
    });
  };

  const sendEmail = (item) => {
    setForm2({
      ...form2,
      orderNo: item.orderNo,
      toUser: item.userEmail,
      backEmail: shopInfo.email,
    });
    setOpen2(true);
  };

  const getOrderList = (data) => {
    requestGET(`shop/source/order/${data.id}`).then((res: any) => {
      setForm1({ ...res });
      ref.current?.setValues({ ...res });
      ref1.current?.setValues({ ...res });
      ref2.current?.setValues({ ...res });
    });
  };

  const formRef = useRef<any>();

  const onSubmit1 = () => {
    requestPUT(`shop/source/order/updateStatus`, { ...form1 }).then(() => {
      Toast.open({ type: "success", message: "操作成功" });
      setOpen1(false);
      ref.current?.reset();
      ref1.current?.reset();
      getList();
    });
  };
  const onSubmit4 = () => {
    requestPUT(`shop/updateDeliveryInfo`, { ...form1 }).then(() => {
      Toast.open({ type: "success", message: "操作成功" });
      setOpen1(false);
      ref2.current?.reset();
      getList();
    });
  };

  const onSubmit2 = () => {
    if (!form2.toUser) {
      return Toast.open({ type: "fail", message: "请输入买家收件邮箱" });
    }
    if (!form2.backEmail) {
      return Toast.open({ type: "fail", message: "请输入买家回件邮箱" });
    }

    Taro.showLoading({ title: "发送中..." });
    requestPOST("shop/shopAddOrEditOrderSendEmail", { ...form2 }).then(() => {
      Toast.open({ type: "success", message: "发送成功" });
      Taro.hideLoading();
      setOpen2(false);
      ref3.current?.reset();
      getList();
    });
  };

  const delOrder = () => {
    Dialog.confirm({
      title: "提示",
      message: "您确定要删除吗？",
      onConfirm() {
        if (!selectId.length) {
          return Toast.open({ type: "fail", message: "请选择一个订单" });
        }
        if (selectId.length > 1) {
          return Toast.open({ type: "fail", message: "只能删除一个订单" });
        }

        const obj = list.find((item) => item.id === selectId[0]);
        if (obj?.isBusinessAdd != 1) {
          return Toast.open({ message: "只能删除卖家帮下订单", type: "fail" });
        }
        requestPOST(`shop/shopDelOrder/${selectId[0]}`).then(() => {
          setCurrent(1);
          getList(1);
          setSelectId([]);
          Toast.open({ type: "success", message: "删除成功" });
        });
      },
    });
  };

  const dowloadFile = () => {
    Dialog.confirm({
      title: "提示",
      message: "您确定要导出吗？",
      onConfirm() {
        if (!selectId.length) {
          return Toast.open({ type: "fail", message: "请选择一个订单" });
        }
        Taro.request({
          url: process.env.TARO_APP_API + "/shop/exportOrderList",
          method: "POST",
          responseType: "arraybuffer",
          data: { ids: selectId },
          header: {
            Authorization: Taro.getStorageSync("token"),
          },
        }).then((res) => {
          const arrayBuffer = res.data;
          const fs = Taro.getFileSystemManager();
          const filePath = `${Taro.env.USER_DATA_PATH}/订单.xlsx`;

          try {
            fs.writeFileSync(filePath, arrayBuffer, "binary");
          } catch (e) {
            console.log(e);
          }

          fs.saveFile({
            tempFilePath: filePath,
            success: (res) => {
              Toast.open({
                type: "success",
                message: `保存成功: ${res.savedFilePath}`,
              });
            },
            fail: (e) => {
              console.log(e);
              Toast.open({ message: "保存失败", type: "fail" });
            },
          });
        });
      },
    });
  };

  const [shopDetails, setShopDetails] = useState<any>([]);

  const getShopDetail = (id) => {
    requestPOST(`shop/shopCommodityDetail/${id}`).then((res: any) => {
      setShopDetails([
        ...shopDetails,
        {
          ...res,
          quantity: 1,
          skuInfo: "",
          selectArr: [],
          specificationItemValue: "",
          subIndex: [],
          totalPrice: (1 * res.presentPrice).toFixed(2),
        },
      ]);
    });
  };

  const onSubmit3 = () => {
    for (let i = 0; i < shopDetails.length; i++) {
      if (!Number(shopDetails[i].quantity)) {
        Toast.open({ type: "fail", message: "请输入数量" });
        return;
      }
      if (!shopDetails[i].specificationItemValue) {
        Toast.open({ type: "fail", message: "请选择型号" });
        return;
      }
    }

    requestPOST("shop/shopAddOrders", {
      ...form3,
      commodityList: shopDetails.map((item) => ({
        ...item,
        commodityId: item.id,
        payPrice: item.totalPrice,
        commodityPrice: item.presentPrice,
      })),
    }).then((res: any) => {
      Toast.open({ type: "success", message: "保存成功" });
      setOpen3(false);
      setShopDetails([]);
      setForm3({});
      ref4.current?.reset();
      getList();
      Taro.nextTick(() => {
        setForm2({ ...form2, orderNo: res.orderNo[0] });
        setOpen2(true);
      });
    });
  };

  const ref4 = useRef<any>();

  useEffect(() => {
    getList();
    getProductList();
  }, []);

  return (
    <View className="taroBox">
      <HeaderSearch />
      <Header />
      <View>
        <GoodsTitle title="订单信息" isMore={false} />
        <View style={{ padding: "14px" }}>
          <View style={{ display: "flex", alignItems: "center", gap: "10px" }}>
            <Button
              size="small"
              variant={active == 0 ? "contained" : "outlined"}
              color="primary"
              onClick={() => {
                setActive(0);
                setCurrent(1);
                getList(1, 0);
              }}
            >
              全部
            </Button>
            <Button
              size="small"
              variant={active == 1 ? "contained" : "outlined"}
              color="primary"
              onClick={() => {
                setActive(1);
                setCurrent(1);
                getList(1, 1);
              }}
            >
              未支付
            </Button>
            <Button
              size="small"
              variant={active == 2 ? "contained" : "outlined"}
              color="primary"
              onClick={() => {
                setActive(2);
                setCurrent(1);
                getList(1, 2);
              }}
            >
              已支付
            </Button>
          </View>
          <View
            style={{
              display: "flex",
              alignItems: "center",
              gap: "10px",
              marginTop: "10px",
            }}
          >
            <Button size="small" color="warning" onClick={() => dowloadFile()}>
              导出
            </Button>
            <Button size="small" color="primary" onClick={() => setOpen3(true)}>
              添加
            </Button>
            <Button size="small" color="danger" onClick={() => delOrder()}>
              删除
            </Button>
          </View>
          <View
            style={{
              display: "flex",
              flexDirection: "column",
              gap: "20px",
              marginTop: "10px",
            }}
          >
            {list.map((item, index) => (
              <Checkbox.Group value={selectId} onChange={setSelectId}>
                <View
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "4px",
                    padding: "10px",
                    boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                    fontSize: "14px",
                    position: "relative",
                  }}
                >
                  <View
                    style={{ position: "absolute", right: "10px", top: "10px" }}
                  >
                    <Checkbox name={item.id}></Checkbox>
                  </View>
                  <View>订单号：{item.orderNo}</View>
                  <View>
                    下单类型：
                    {item.isBusinessAdd == 1
                      ? "商城代下单"
                      : item.isBusinessAdd == 2
                      ? "妙手代下单"
                      : item.isBusinessAdd == 3
                      ? "后台下单"
                      : "用户下单"}
                  </View>
                  <View>订单总额：{item.totalPrice}</View>
                  <View>优惠金额：{item.discountPrice}</View>
                  <View>支付金额：{item.payPrice}</View>
                  <View>
                    支付状态：
                    {item.status == 0
                      ? "未支付"
                      : item.status == 1
                      ? "已支付"
                      : item.status == 2
                      ? "退款"
                      : ""}
                  </View>
                  <View>付款时间：{item.createTime}</View>
                  <View>发货单号：{item.orderNo}</View>
                  <View>下单用户：{item.contacts}</View>
                  <View
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: "10px",
                      flexWrap: "wrap",
                    }}
                  >
                    <Button
                      size="small"
                      color="success"
                      onClick={() => {
                        getOrderList(item);
                        setOpen1(true);
                      }}
                    >
                      详情
                    </Button>
                    {item.isBusinessAdd == 1 && item.status == 0 && (
                      <Button
                        size="small"
                        color="primary"
                        onClick={() => sendEmail(item)}
                      >
                        发送邮件
                      </Button>
                    )}
                    {((item.status == 0 && item.isBusinessAdd == 0) ||
                      item.status != 1) && (
                      <Button
                        size="small"
                        color="danger"
                        onClick={() => cancelOrder(item)}
                      >
                        取消订单
                      </Button>
                    )}
                    {item.status == 1 &&
                      (item.payMode == 2 || item.payMode == 3) &&
                      item.payVoucher != null &&
                      item.confirmPay == 0 && (
                        <Button
                          size="small"
                          color="primary"
                          onClick={() => confirmOrderPayApi(item)}
                        >
                          确认支付
                        </Button>
                      )}
                    {item.isBusinessAdd == 1 &&
                      item.status == 0 &&
                      item.isEmail == 1 && (
                        <Button
                          size="small"
                          color="primary"
                          onClick={() => shopConfirmOrderPay(item)}
                        >
                          确认支付
                        </Button>
                      )}
                    {item.payVoucher != null && (
                      <Button
                        size="small"
                        color="primary"
                        onClick={() => viewImage(item)}
                      >
                        查看凭证
                      </Button>
                    )}
                  </View>
                  <View
                    style={{
                      margin: "5px 0",
                      display: "flex",
                      gap: "5px",
                      justifyContent: "center",
                      color: "#1989fa",
                      cursor: "pointer",
                      fontSize: "14px",
                    }}
                    onClick={() => handleShow(item, index)}
                  >
                    查看下单商品信息
                    <ArrowDown color="#1989fa" />
                  </View>
                  {item.show && (
                    <View
                      style={{
                        display: "flex",
                        flexDirection: "column",
                        gap: "20px",
                      }}
                    >
                      {item.orderDetailVos.map((order) => (
                        <View
                          style={{
                            display: "flex",
                            flexDirection: "column",
                            gap: "4px",
                          }}
                        >
                          <View
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: "10px",
                            }}
                          >
                            <View style={{ width: "100px" }}>
                              <Image
                                src={process.env.TARO_APP_API + order.image}
                                width={100}
                                height={100}
                                mode="aspectFill"
                                fallback={<PhotoFail />}
                              />
                            </View>
                            <View>
                              <View
                                style={{
                                  display: "grid",
                                  gridTemplateColumns: "repat(2,1fr)",
                                }}
                              >
                                <View
                                  style={{
                                    textOverflow: "ellipsis",
                                    overflow: "hidden",
                                    whiteSpace: "nowrap",
                                  }}
                                >
                                  {order.commodityName}
                                </View>
                                <View>sku：{order.specifications}</View>
                                <View>购买数量：{order.quantity}</View>
                                <View>单价：{order.price}</View>
                                <View>运费：{order.freightCharge || 0}</View>
                                <View>小计：{order.totalPrice}</View>
                              </View>
                            </View>
                          </View>
                          <Button
                            size="small"
                            color="primary"
                            variant="outlined"
                            onClick={() => editPrice(item, order)}
                          >
                            修改价格
                          </Button>
                        </View>
                      ))}
                    </View>
                  )}
                </View>
              </Checkbox.Group>
            ))}
          </View>
        </View>
        <View style={{ marginBlock: "1.25rem", padding: "0 .875rem" }}>
          <Pagination
            current={current}
            siblingCount={1}
            count={count}
            onChange={(page) => handleChange(page)}
          >
            <Pagination.Item type="start-ellipsis" />
            <Pagination.Item type="end-ellipsis" />
          </Pagination>
        </View>
      </View>
      <Footer />

      <Popup
        open={open}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => setOpen(false)}
        lock={false}
      >
        <ScrollView style={{ maxHeight: "90vh" }} scrollY>
          <View style={{ width: "90vw", padding: "14px" }}>
            <Form
              ref={formRef}
              defaultValues={form}
              onSubmit={() => onSubmit()}
            >
              <Cell.Group inset style={{ margin: 0 }}>
                <Form.Item
                  name="price"
                  rules={[{ required: true, message: "请输入价格" }]}
                >
                  <Form.Label>价格</Form.Label>
                  <Form.Control>
                    <Input
                      value={form.price}
                      onChange={(e) =>
                        setForm({ ...form, price: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="quantity"
                  rules={[{ required: true, message: "请输入数量" }]}
                >
                  <Form.Label>数量</Form.Label>
                  <Form.Control>
                    <Input
                      value={form.quantity}
                      onChange={(e) =>
                        setForm({ ...form, quantity: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                }}
              >
                <Button shape="round" block color="primary" formType="submit">
                  保存
                </Button>
              </View>
            </Form>
          </View>
        </ScrollView>
      </Popup>

      <Popup
        open={open1}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => setOpen1(false)}
        lock={false}
      >
        <ScrollView style={{ maxHeight: "90vh" }} scrollY>
          <View style={{ width: "90vw", padding: "14px" }}>
            <Form ref={ref} defaultValues={form1} onSubmit={() => onSubmit1()}>
              <View style={{ fontSize: "16px", marginBottom: "20px" }}>
                订单信息
              </View>
              <Cell.Group style={{ margin: 0 }} inset>
                <Form.Item name="orderNo">
                  <Form.Label>订单号</Form.Label>
                  <Form.Control>{form1.orderNo}</Form.Control>
                </Form.Item>
                <Form.Item name="totalPrice">
                  <Form.Label>订单总价</Form.Label>
                  <Form.Control>{form1.totalPrice}</Form.Control>
                </Form.Item>
                <Form.Item name="discountPrice">
                  <Form.Label>优惠金额</Form.Label>
                  <Form.Control>{form1.discountPrice}</Form.Control>
                </Form.Item>
                <Form.Item name="createTime">
                  <Form.Label>创建时间</Form.Label>
                  <Form.Control>{form1.createTime}</Form.Control>
                </Form.Item>
                <Form.Item name="payPrice">
                  <Form.Label>支付价格</Form.Label>
                  <Form.Control>{form1.payPrice}</Form.Control>
                </Form.Item>
                <Form.Item name="payMode">
                  <Form.Label>支付方式</Form.Label>
                  <Form.Control>
                    {form1.payMode == 1
                      ? "PayPal支付"
                      : form1.payMode == 2
                      ? "收款码"
                      : form1.payMode == 3
                      ? "银行卡"
                      : form1.payMode == 4
                      ? "PayPal支付统一收款"
                      : "未支付"}
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="status"
                  rules={[{ required: true, message: "请选择状态" }]}
                >
                  <Form.Label>状态</Form.Label>
                  <Form.Control>
                    <Radio.Group
                      value={form1.status}
                      onChange={(value) =>
                        setForm1({ ...form1, status: value })
                      }
                    >
                      <Radio name={-1}>删除</Radio>
                      <Radio name={0}>未支付</Radio>
                      <Radio name={1}>已支付</Radio>
                      <Radio name={2}>已退款</Radio>
                      <Radio name={3}>已取消</Radio>
                    </Radio.Group>
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="isComplete"
                  rules={[{ required: true, message: "请选择确认订单" }]}
                >
                  <Form.Label>确认订单</Form.Label>
                  <Form.Control>
                    <Radio.Group
                      value={form1.isComplete}
                      onChange={(value) =>
                        setForm1({ ...form1, isComplete: value })
                      }
                    >
                      <Radio name={0}>未完成</Radio>
                      <Radio name={1}>已完成</Radio>
                    </Radio.Group>
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                }}
              >
                <Button shape="round" block color="primary" formType="submit">
                  提交
                </Button>
              </View>
            </Form>

            <View style={{ fontSize: "16px", margin: "20px 0" }}>商品清单</View>
            <View
              style={{ display: "flex", flexDirection: "column", gap: "20px" }}
            >
              {form1.orderDetailList &&
                form1.orderDetailList.map((item1) => (
                  <View
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: "10px",
                      padding: "10px",
                      boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                    }}
                  >
                    <View style={{ width: "100px" }}>
                      <Image
                        src={process.env.TARO_APP_API + item1.image}
                        width={100}
                        height={164}
                        mode="aspectFill"
                        fallback={<PhotoFail />}
                      />
                    </View>
                    <View
                      style={{
                        fontSize: "14px",
                        display: "flex",
                        flexDirection: "column",
                        gap: "4px",
                        flex: 1,
                        overflow: "hidden",
                      }}
                    >
                      <View
                        style={{
                          textOverflow: "ellipsis",
                          overflow: "hidden",
                          whiteSpace: "nowrap",
                        }}
                      >
                        {item1.commodityName}
                      </View>
                      <View>订单号：{item1.orderNo}</View>
                      <View>商品SKU：{item1.specifications}</View>
                      <View>购买数量：{item1.quantity}</View>
                      <View>单价：{item1.price}</View>
                      <View>运费：{item1.freightCharge}</View>
                      <View>
                        小记：
                        {(
                          item1.price * item1.quantity +
                          item1.freightCharge
                        ).toFixed(2)}
                      </View>
                    </View>
                  </View>
                ))}
            </View>
            <Form ref={ref1} defaultValues={form1} onSubmit={() => onSubmit1()}>
              <View style={{ fontSize: "16px", margin: "20px 0" }}>
                配送地址
              </View>
              <Cell.Group style={{ margin: 0 }} inset>
                <Form.Item
                  name="contacts"
                  rules={[{ required: true, message: "请输入收货人" }]}
                >
                  <Form.Label>收货人</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.contacts}
                      onChange={(e) =>
                        setForm1({ ...form1, contacts: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="phone"
                  rules={[{ required: true, message: "请输入手机" }]}
                >
                  <Form.Label>手机</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.phone}
                      onChange={(e) =>
                        setForm1({ ...form1, phone: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="country"
                  rules={[{ required: true, message: "请输入国家" }]}
                >
                  <Form.Label>国家</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.country}
                      onChange={(e) =>
                        setForm1({ ...form1, country: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="city"
                  rules={[{ required: true, message: "请输入城市" }]}
                >
                  <Form.Label>城市</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.city}
                      onChange={(e) =>
                        setForm1({ ...form1, city: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="address"
                  rules={[{ required: true, message: "请输入地址" }]}
                >
                  <Form.Label>地址</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.address}
                      onChange={(e) =>
                        setForm1({ ...form1, address: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="postCode"
                  rules={[{ required: true, message: "请输入邮政编码" }]}
                >
                  <Form.Label>邮政编码</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.postCode}
                      onChange={(e) =>
                        setForm1({ ...form1, postCode: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="email"
                  rules={[{ required: true, message: "请输入邮箱" }]}
                >
                  <Form.Label>邮箱</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.email}
                      onChange={(e) =>
                        setForm1({ ...form1, email: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                }}
              >
                <Button shape="round" block color="primary" formType="submit">
                  提交
                </Button>
              </View>
            </Form>
            <Form ref={ref2} defaultValues={form1} onSubmit={() => onSubmit4()}>
              <View style={{ fontSize: "16px", margin: "20px 0" }}>
                配送信息
              </View>
              <Cell.Group style={{ margin: 0 }} inset>
                <Form.Item
                  name="isDelivery"
                  rules={[{ required: true, message: "请选择是否发货" }]}
                >
                  <Form.Label>是否发货</Form.Label>
                  <Form.Control>
                    <Radio.Group
                      value={form1.isDelivery}
                      onChange={(value) =>
                        setForm1({ ...form1, isDelivery: value })
                      }
                    >
                      <Radio name={0}>未发货</Radio>
                      <Radio name={1}>已发货</Radio>
                    </Radio.Group>
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="logisticsMode"
                  rules={[{ required: true, message: "请输入物流方式" }]}
                >
                  <Form.Label>物流方式</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.logisticsMode}
                      onChange={(e) =>
                        setForm1({ ...form1, logisticsMode: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item name="logisticsInfo">
                  <Form.Label>最新物流信息</Form.Label>
                  <Form.Control>{form1.logisticsInfo}</Form.Control>
                </Form.Item>
                <Form.Item name="logisticsCode">
                  <Form.Label>物流商简码</Form.Label>
                  <Form.Control>{form1.logisticsCode}</Form.Control>
                </Form.Item>
                <Form.Item name="logisticsUpdateTime">
                  <Form.Label>物流信息更新时间</Form.Label>
                  <Form.Control>{form1.logisticsUpdateTime}</Form.Control>
                </Form.Item>
                <Form.Item
                  name="deliveryOrderNo"
                  rules={[{ required: true, message: "请输入发送单号" }]}
                >
                  <Form.Label>发送单号</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.deliveryOrderNo}
                      onChange={(e) =>
                        setForm1({ ...form1, deliveryOrderNo: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="freightPrice"
                  rules={[{ required: true, message: "请输入运费" }]}
                >
                  <Form.Label>运费</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.freightPrice}
                      onChange={(e) =>
                        setForm1({ ...form1, freightPrice: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="parcelWeight"
                  rules={[{ required: true, message: "请输入重量" }]}
                >
                  <Form.Label>重量</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.parcelWeight}
                      onChange={(e) =>
                        setForm1({ ...form1, parcelWeight: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="commodityNum"
                  rules={[{ required: true, message: "请输入产品数量" }]}
                >
                  <Form.Label>产品数量</Form.Label>
                  <Form.Control>
                    <Input
                      value={form1.commodityNum}
                      onChange={(e) =>
                        setForm1({ ...form1, commodityNum: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                  paddingBottom: "20px",
                }}
              >
                <Button shape="round" block color="primary" formType="submit">
                  提交
                </Button>
              </View>
            </Form>
          </View>
        </ScrollView>
      </Popup>

      <Popup
        open={open2}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => {
          ref3.current?.reset();
          setOpen2(false);
        }}
        lock={false}
      >
        <ScrollView style={{ maxHeight: "90vh" }} scrollY>
          <View style={{ width: "90vw", padding: "14px" }}>
            <View style={{ marginBottom: "20px" }}>发送收款信息邮箱</View>
            <Form ref={ref3} defaultValues={form2} onSubmit={() => onSubmit2()}>
              <Cell.Group style={{ margin: 0 }} inset>
                <Form.Item name="orderNo">
                  <Form.Label>订单号</Form.Label>
                  <Form.Control>{form2.orderNo}</Form.Control>
                </Form.Item>
                <Form.Item name="toUser">
                  <Form.Label>买家收件邮箱</Form.Label>
                  <Form.Control>
                    <Input
                      value={form2.toUser}
                      onChange={(e) =>
                        setForm2({ ...form2, toUser: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item name="backEmail">
                  <Form.Label>买家回件邮箱</Form.Label>
                  <Form.Control>
                    <Input
                      value={form2.backEmail}
                      onChange={(e) =>
                        setForm2({ ...form2, backEmail: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                }}
              >
                <Button shape="round" block color="primary" formType="submit">
                  提交
                </Button>
              </View>
            </Form>
          </View>
        </ScrollView>
      </Popup>

      <Popup
        open={open3}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => {
          setShopDetails([]);
          setForm3({});
          ref4.current?.reset();
          setOpen3(false);
        }}
        lock={false}
      >
        <ScrollView style={{ maxHeight: "90vh" }} scrollY>
          <View style={{ width: "90vw", padding: "14px" }}>
            <Form ref={ref4} defaultValues={form3} onSubmit={() => onSubmit3()}>
              <Cell.Group style={{ margin: 0 }} inset>
                <Form.Item name="commodityId">
                  <Form.Control>
                    <Field
                      label="搜索产品"
                      ref={itemRef}
                      name="picker"
                      clickable
                      isLink
                      style={{ padding: "0px" }}
                    >
                      <Input
                        readonly
                        placeholder="搜索产品"
                        onClick={() => setOpen4(true)}
                      />
                    </Field>
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View>
                {shopDetails.map((item, index) => (
                  <View
                    key={item.id}
                    style={{
                      padding: "10px",
                      boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                    }}
                  >
                    <Field label="id">{item.id}</Field>
                    <Field label="商品名称">
                      <View
                        style={{
                          textOverflow: "ellipsis",
                          overflow: "hidden",
                          whiteSpace: "nowrap",
                          width: "182px",
                        }}
                      >
                        {item.commodityName}
                      </View>
                    </Field>
                    <Field label="价格">{item.presentPrice}</Field>
                    <Field label="数量">
                      <Input
                        placeholder="请输入数量"
                        value={item.quantity}
                        onChange={(e: any) => {
                          shopDetails.splice(index, 1, {
                            ...item,
                            quantity: e.detail.value,
                            totalPrice: (
                              e.detail.value * item.presentPrice
                            ).toFixed(2),
                          });
                          setShopDetails([...shopDetails]);
                        }}
                      />
                    </Field>
                    <Field label="总价">{item.totalPrice}</Field>
                    <Field label="规格">
                      {item.skuParentList &&
                        item.skuParentList.length &&
                        item.skuParentList[0].skuChildList.map(
                          (item1, index1) => (
                            <View
                              style={{
                                display: "flex",
                                gap: "4px",
                                fontSize: "12px",
                                border:
                                  item.specificationItemValue ===
                                  item1.skuValueId
                                    ? "1px solid #51ac89"
                                    : "1px solid #ddd",
                                width: "80px",
                              }}
                              onClick={() => {
                                shopDetails.splice(index, 1, {
                                  ...item,
                                  presentPrice:
                                    item.skuItemList[index1].presentPrice,
                                  totalPrice:
                                    item.quantity *
                                    item.skuItemList[index1].presentPrice,
                                  selectArr: [item1.skuValueId],
                                  specificationItemValue: item1.skuValueId,
                                  skuInfo: item1.skuValue,
                                  subIndex: [index1],
                                });
                                setShopDetails([...shopDetails]);
                              }}
                            >
                              <Image
                                src={process.env.TARO_APP_API + item1.skuImgUrl}
                                width={30}
                                height={30}
                                mode="aspectFill"
                                fallback={<PhotoFail />}
                              />
                              <View
                                style={{
                                  flex: 1,
                                  textOverflow: "ellipsis",
                                  overflow: "hidden",
                                  whiteSpace: "nowrap",
                                  display: "grid",
                                  alignItems: "center",
                                }}
                              >
                                {item1.skuValue}
                              </View>
                            </View>
                          )
                        )}
                    </Field>

                    <View>
                      <Button
                        size="small"
                        color="danger"
                        block
                        variant="outlined"
                        onClick={() => {
                          Dialog.confirm({
                            title: "提示",
                            message: "您确定要删除吗？",
                            backdrop: {
                              style: { zIndex: 1010 },
                            },
                            style: {
                              zIndex: 1011,
                            },
                            onConfirm() {
                              shopDetails.splice(index, 1);
                              setShopDetails([...shopDetails]);
                              Toast.open({
                                type: "success",
                                message: "删除成功",
                              });
                            },
                          });
                        }}
                      >
                        删除
                      </Button>
                    </View>
                  </View>
                ))}
              </View>
              <Cell.Group style={{ margin: 0 }} inset>
                <Form.Item
                  name="remark"
                >
                  <Form.Label>备注</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.remark}
                      onChange={(e) =>
                        setForm3({ ...form3, remark: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="userEmail"
                  rules={[{ required: true, message: "请输入消费者邮箱" }]}
                >
                  <Form.Label>消费者邮箱</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.userEmail}
                      onChange={(e) =>
                        setForm3({ ...form3, userEmail: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="contacts"
                  rules={[{ required: true, message: "请输入联系人" }]}
                >
                  <Form.Label>联系人</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.contacts}
                      onChange={(e) =>
                        setForm3({ ...form3, contacts: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="phone"
                  rules={[{ required: true, message: "请输入电话" }]}
                >
                  <Form.Label>电话</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.phone}
                      onChange={(e) =>
                        setForm3({ ...form3, phone: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="country"
                  rules={[{ required: true, message: "请输入国家" }]}
                >
                  <Form.Label>国家</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.country}
                      onChange={(e) =>
                        setForm3({ ...form3, country: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="city"
                  rules={[{ required: true, message: "请输入城市" }]}
                >
                  <Form.Label>城市</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.city}
                      onChange={(e) =>
                        setForm3({ ...form3, city: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="address"
                  rules={[{ required: true, message: "请输入地址" }]}
                >
                  <Form.Label>地址</Form.Label>
                  <Form.Control>
                    <Textarea
                      value={form3.address}
                      onChange={(e) =>
                        setForm3({ ...form3, address: e.detail.value })
                      }
                      style={{ height: "80px" }}
                      limit={255}
                      placeholder="请输入地址"
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="email"
                  rules={[{ required: true, message: "请输入收货邮箱" }]}
                >
                  <Form.Label>收货邮箱</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.email}
                      onChange={(e) =>
                        setForm3({ ...form3, email: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="postCode"
                  rules={[{ required: true, message: "请输入邮政编码" }]}
                >
                  <Form.Label>邮政编码</Form.Label>
                  <Form.Control>
                    <Input
                      value={form3.postCode}
                      onChange={(e) =>
                        setForm3({ ...form3, postCode: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                  paddingBottom: "20px",
                }}
              >
                <Button shape="round" block color="primary" formType="submit">
                  添加
                </Button>
              </View>
            </Form>
          </View>
        </ScrollView>
      </Popup>

      <ConfigProvider
        theme={{
          backdropZIndex: 1010,
        }}
      >
        <Popup
          open={open4}
          rounded
          placement="bottom"
          onClose={setOpen4}
          style={{ zIndex: 1011 }}
        >
          <Picker
            title="搜索产品"
            columns={productList}
            onCancel={() => setOpen4(false)}
            onConfirm={(newValue, obj) => {
              itemRef.current?.setValue(obj[0].label);
              setForm3({ ...form3, commodityId: newValue[0] });
              getShopDetail(newValue[0]);
              setOpen4(false);
            }}
          ></Picker>
        </Popup>
      </ConfigProvider>
    </View>
  );
}
